package cn.tedu._03vehicle.base.exception;

import cn.tedu._03vehicle.base.response.JsonResult;
import cn.tedu._03vehicle.base.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

//@ControllerAdvice
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    //@ResponseBody
    //第1个异常处理方法：可以处理IllegalArgumentException类型异常
    public JsonResult doHandleIllegalArgumentException(IllegalArgumentException ex) {
        String data = ex.getMessage();
        log.error("doHandleIllagalArgumentException:"+data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }
    //第2个异常处理方法：可以处理ConstraintViolationException类型异常
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex){
        String data = ex.getMessage().split(":")[1].trim();
        log.error("doHandleConstraintViolationException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);

    }
    //第3个异常处理方法：可以处理MethodArgumentNotValidException类型异常
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex){
        String data = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidaException:"+data);
        return new JsonResult(StatusCode.VALIDATED_ERROR,data);
    }
    //第4个异常处理方法：可以处理所有的RuntimeException类型异常及其子类异常的处理方法
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex){
        String data = ex.getMessage();
        log.error("doHandleRuntimeException:"+data);
        return new JsonResult(StatusCode.OPERATION_FAILED,data);
    }
    //第5个异常处理方法：可以处理所有异常的处理方法，一般最后加
    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex){
        String data = ex.getMessage();
        log.error("doHandleThrowable:"+data);
        return new JsonResult(StatusCode.THROWABLE_ERROR,data);
    }
}
